package handlers

import (
	"book-mgmt-sys/models"
	"github.com/gin-gonic/gin"
	"path/filepath"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || len(title) < 10 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "正文标题不可为空，并且长度10字以内",
		})
		return
	}
	if content == "" || len(content) < 10 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "正文内容不可为空，并且长度50字以内",
		})
		return
	}
	data := models.Book{
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片错误",
		})
		return
	}
	allow := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
	}
	ext := filepath.Ext(file.Filename)
	if !allow[ext] {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "Gin图片上传的格式限制png、jpg、jpeg",
		})
		return
	}
	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	}
	url := "http://" + c.Request.Host + "/" + path
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"url":  url,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))

	var count int64
	models.DB.Model(&models.Book{}).Count(&count)

	offset := (page - 1) * size

	var book []models.Book
	err := models.DB.Limit(size).Offset(offset).Find(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"book":  book,
			"count": count,
		},
	})
	return
}
